package ServerConnection;

import Client.ServerInfo;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

public class SearchUserServer {
    public static void main(String[] args) {
        try {
            DatabaseServer databaseServer = new DatabaseServer();
            ServerSocket serverSocket = new ServerSocket(ServerInfo.SERVER_SEARCHUSER_PORT);
            System.out.println("搜索用户服务成功启动！");
            Socket socket;
            while (true) {
                socket = serverSocket.accept();
                Thread handle = new Thread(new ThreadHandleSearchUser(socket, databaseServer));
                handle.start();
            }
        } catch (IOException e) {
            System.out.println("WARNING:AccountAddFriendServer Init fail,Reason:socket has ioException.");
        }
    }
}


/**该类是服务端用来处理搜索用户功能的线程类*/
 class ThreadHandleSearchUser implements Runnable{
    Socket socket = null;
    boolean res;
    String userId;
    DatabaseServer databaseServer;

    public ThreadHandleSearchUser(Socket socket, DatabaseServer databaseServer) {
        super();
        this.socket = socket;
        this.databaseServer = databaseServer;
    }

    @Override
    public void run() {
        try {
            InputStream inputStream = socket.getInputStream();
            InputStreamReader inputStreamReader=new InputStreamReader(inputStream);//包装成字符流，提高效率
            BufferedReader bufferedReader=new BufferedReader(inputStreamReader);//缓冲区
            String userId = bufferedReader.readLine();//获得用户id

            String sql = "SELECT * FROM UserAccount WHERE Uid='" + userId + "';";
            System.out.println("sql:" + sql);
            res = databaseServer.doExecute(sql);

            System.out.println("res:"+res);
            //返还执行的结果到客户端。
            OutputStream outputStream = socket.getOutputStream();
            outputStream.write(String.valueOf(res).getBytes(StandardCharsets.UTF_8));

            inputStream.close();
            outputStream.close();
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
